<script setup lang="ts">
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { computed, onMounted, ref } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
import type { Article } from '@/types/article'
import type { Category } from '@/types/category'
import { getCategoryList } from '@/services/category'
import { add, update, getArticleList, deleteArticle } from '@/services/article'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { useUserStore } from '@/stores'
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus'
// 国际化
const language = ref('zh-cn')
const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))

onMounted(async () => {
  await loadCategoryList()
  getArticles()
})

// 文章分类数据模型
const categorys = ref<Category[]>([])
const loadCategoryList = async () => {
  const res = await getCategoryList()
  categorys.value = res.data
}
// 用户搜索时选中的分类id
const categoryId = ref()
// 用户搜索时选中的发布状态
const state = ref()
// 文章列表数据模型
const articles = ref<Article[]>()
// 分页条数据模型
const pageNum = ref(1) //当前页
const total = ref(0) //总条数
const pageSize = ref(5) //每页条数

// 搜索
const getArticles = async () => {
  const res = await getArticleList(
    pageNum.value,
    pageSize.value,
    categoryId.value,
    state.value
  )
  total.value = res.data.total
  articles.value = res.data.items
  // 根据categoryId为categoryName赋值
  articles.value.forEach((article) => {
    article.categoryName = categorys.value.find(
      (category) => category.id === article.categoryId
    )?.categoryName
  })
}
// 当每页条数发生了变化，调用此函数
const onSizeChange = async (size: number) => {
  pageSize.value = size
  getArticles()
}
// 当前页码发生变化，调用此函数
const onCurrentChange = async (num: number) => {
  pageNum.value = num
  getArticles()
}

// -------------------添加文章---------------------
const store = useUserStore()
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const articleModel = ref<Article>({})
//上传成功的回调函数
const uploadSuccess: UploadProps['onSuccess'] = (result) => {
  articleModel.value.coverImg = result.data
}
//添加文章
const showAdd = () => {
  //清空数据
  articleModel.value = {}
  //开抽屉
  visibleDrawer.value = true
  title.value = '添加文章'
}
const addArticle = async (state: '已发布' | '草稿') => {
  articleModel.value.state = state
  if (
    !articleModel.value.title ||
    !articleModel.value.content ||
    !articleModel.value.coverImg ||
    !articleModel.value.state ||
    !articleModel.value.categoryId
  )
    return ElMessage.success('表单内容填写不完整')
  // 发请求
  await add(articleModel.value)
  // 请求成功
  ElMessage.success('添加成功')
  //再次调用getArticles,获取文章
  getArticles()
  //隐藏抽屉
  visibleDrawer.value = false
  //清空数据
  articleModel.value = {}
}
// -------------------编辑文章---------------------
const title = ref('')
const showUpdate = (row: Article) => {
  //清空数据
  articleModel.value = {}
  // 开抽屉
  visibleDrawer.value = true
  title.value = '编辑文章'
  // 数据回显
  articleModel.value = row
}
const updateArticle = async (state: '已发布' | '草稿') => {
  articleModel.value.state = state
  // 参数校验
  if (
    !articleModel.value.id ||
    !articleModel.value.title ||
    !articleModel.value.content ||
    !articleModel.value.coverImg ||
    !articleModel.value.state ||
    !articleModel.value.categoryId
  )
    return ElMessage.success('表单内容填写不完整')
  // 发请求
  await update(articleModel.value)
  // 请求成功
  ElMessage.success('修改成功')
  //再次调用getArticles,获取文章
  getArticles()
  //隐藏抽屉
  visibleDrawer.value = false
  //清空数据
  articleModel.value = {}
}
// -------------------删除文章---------------------
const del = async (id: number) => {
  try {
    // 是否确定删除
    await ElMessageBox.confirm('确定删除吗?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 发送请求
    await deleteArticle(id)
    // 请求成功
    ElMessage.success('删除成功')
    // 重新加载列表
    getArticles()
  } catch (error) {
    ElMessage.info('取消删除')
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>文章管理</span>
        <div class="extra">
          <el-button @click="showAdd" type="primary"> 添加文章 </el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="文章分类：">
        <el-select placeholder="请选择" v-model="categoryId">
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.categoryName"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="已发布" value="已发布"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getArticles">搜索</el-button>
        <el-button
          @click="
            () => {
              categoryId = undefined
              state = undefined
            }
          "
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%">
      <el-table-column
        label="文章标题"
        width="400"
        prop="title"
      ></el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="发表时间" prop="createTime"> </el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            @click="showUpdate(row)"
            :icon="Edit"
            circle
            plain
            type="primary"
          ></el-button>
          <el-button
            @click="del(row.id)"
            :icon="Delete"
            circle
            plain
            type="danger"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-config-provider :locale="locale">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-config-provider>
  </el-card>
  <!-- 抽屉 -->
  <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
    <!-- 添加文章表单 -->
    <el-form :model="articleModel" label-width="100px">
      <el-form-item label="文章标题">
        <el-input
          v-model="articleModel.title"
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <el-select placeholder="请选择" v-model="articleModel.categoryId">
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.categoryName"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面">
        <!-- 
            auto-upload:设置是否自动上传
            show-file-list:是否显示已上传文件列表
            action:设置服务器接口路径
            name:设置上传的文件字段名
            headers:设置上传的请求头
            on-success:设置上传成功的回调函数
        -->
        <!-- 
          注意：
          1. 由于这个请求时el-upload自动发送的异步请求，并没有使用咱们的request.js请求工具，
          所以在请求的路径上，需要加上/api, 这个时候请求代理才能拦截到这个请求，转发到后台服务器上
          2. 要携带请求头
          3. 在成功的回调函数中，可以拿到服务器响应的数据
         -->
        <el-upload
          class="avatar-uploader"
          :auto-upload="true"
          :show-file-list="false"
          action="/api/upload"
          name="file"
          :headers="{ Authorization: store.token }"
          :on-success="uploadSuccess"
        >
          <img
            v-if="articleModel.coverImg"
            :src="articleModel.coverImg"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="articleModel.content"
            contentType="html"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="
            title === '添加文章'
              ? addArticle('已发布')
              : updateArticle('已发布')
          "
        >
          发布
        </el-button>
        <el-button
          type="info"
          @click="
            title === '添加文章' ? addArticle('草稿') : updateArticle('草稿')
          "
        >
          草稿
        </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
